//
//  JTSegmentView.swift
//  Singapore Customer App
//
//  Created by Kiyo on 2021/6/23.
//

import UIKit

public class JTSegmentView: UIView {
    
    private lazy var sliderView: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: itemSpace * 2, height: sliderHeight))
        v.backgroundColor = UIColor(red: 230.0/255.0, green: 38.0/255.0, blue: 44.0/255.0, alpha: 1)
        return v
    }()
    
    private lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        
        let v = UICollectionView(frame: .zero, collectionViewLayout: layout)
        v.delegate = self
        v.dataSource = self
        v.backgroundColor = .clear
        v.showsHorizontalScrollIndicator = false
        v.showsVerticalScrollIndicator = false
        v.registerNormalClass(JTSegmentTextCell.self)
        return v
    }()
    
    public var textFont: UIFont = UIFont.systemFont(ofSize: 14) {
        didSet {
            collectionView.reloadData()
        }
    }
    
    public var itemSpace: CGFloat = 20 {
        didSet {
            scrollTo(selectedIdx)
            collectionView.reloadData()
        }
    }
    
    public var sliderHeight: CGFloat = 30 {
        didSet {
            sliderView.layer.cornerRadius = sliderHeight/2
            scrollTo(selectedIdx)
        }
    }
    
    public var didSelectedIdx: ((Int)-> Void)?
    
    
    private var titles: [String]
    private var selectedIdx: Int = 0
    private var selectedText: String = ""
    
    

    public init(items: [String]) {
        
        titles = items
        super.init(frame: .zero)
        
        setupSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        sliderView.frame = CGRect(x: sliderView.frame.minX, y: (frame.height - sliderHeight)/2, width: sliderView.frame.width, height: sliderView.frame.height)
        collectionView.frame = bounds
    }
    
    private func setupSubviews() {
        
        backgroundColor = .white
        layer.borderWidth = 1
        layer.borderColor = UIColor(red: 230.0/255.0, green: 38.0/255.0, blue: 44.0/255.0, alpha: 1).cgColor
        
        addSubview(sliderView)
        addSubview(collectionView)
        
        guard titles.count > 0 else { return }
        
        selectedText = titles[0]
        collectionView.reloadData()
    }
    
    //MARK:- Private
    private func scrollTo(_ idx: Int) {
        
        guard titles.count > 0 else { return }
        
        var x: CGFloat = 0
        for idx in 0..<selectedIdx {
            let w = titles[idx].sizeForText(font: textFont, availableWidth: UIScreen.main.bounds.width).width + itemSpace * 2
            x += w
        }
        
        let width = titles[selectedIdx].sizeForText(font: textFont, availableWidth: UIScreen.main.bounds.width).width + itemSpace * 2
        UIView.animate(withDuration: 0.25) {
            self.sliderView.frame = CGRect(x: x, y: (self.frame.height - self.sliderHeight)/2, width: width, height: self.sliderHeight)
        } completion: { finish in
            
        }
    }
}

//MARK:- UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
extension JTSegmentView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let size: CGSize = titles[indexPath.row].sizeForText(font: textFont, availableWidth: UIScreen.main.bounds.width)
        return CGSize(width: size.width + itemSpace * 2, height: frame.height)
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return .zero
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return titles.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JTSegmentTextCell.identifier, for: indexPath) as! JTSegmentTextCell
        cell.contentLabel.font = textFont
        cell.config(text: titles[indexPath.row], selectedText: selectedText)
        return cell
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        selectedIdx = indexPath.row
        selectedText = titles[indexPath.row]
        scrollTo(indexPath.row)
        didSelectedIdx?(indexPath.row)
        collectionView.reloadData()
    }
}


class JTSegmentTextCell: UICollectionViewCell {
    
    lazy var contentLabel: JTLabel = {
        let lbl = JTLabel(frame: .zero)
        lbl.textColor = UIColor(red: 230.0/255.0, green: 38.0/255.0, blue: 44.0/255.0, alpha: 1)
        lbl.font = UIFont.systemFont(ofSize: 14)
        lbl.textAlignment = .center
        lbl.numberOfLines = 1
        return lbl
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        contentLabel.frame = contentView.bounds
    }
    
    private func setupSubviews() {
        contentView.addSubview(contentLabel)
    }
    
    func config(text: String, selectedText: String) {
        
        if text == selectedText {
            contentLabel.textColor = .white
        }
        else {
            contentLabel.textColor = UIColor(red: 230.0/255.0, green: 38.0/255.0, blue: 44.0/255.0, alpha: 1)
        }
        contentLabel.text = text
    }
}
